# -*- coding: utf-8 -*-

import os
import sys
from contextlib import closing
import jinja2
import hashlib
import werkzeug.utils
import uuid
import openerp
from openerp import http
from openerp.http import request
from openerp.modules.registry import RegistryManager
from reportlab.graphics.barcode import createBarcodeDrawing

# wifidog ping
if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)

SUPERUSER_ID = 1


class wifi_dog(http.Controller):

    @http.route('/weixin/wifidog_ping', auth='public')
    def weixin_wifidog_ping(self, **kw):
        return 'Pong'

    # wifidog login
    @http.route('/weixin/wifidog_login', auth='public')
    def weixin_wifidog_login(self, **kw):
        uid = request.session.uid
        db_name = request.session.db
        mac_address = kw.get('mac')
        gw_address = kw.get('gw_address')
        gw_port = kw.get('gw_port')
        ip = kw.get('ip')
        db = RegistryManager.get(db_name)
        if uid and mac_address:

            # token = 'token'
            token_md5 = hashlib.md5()
            token_md5.update('%s%s' % (mac_address, uid))
            token = token_md5.hexdigest()
            url = 'http://' + gw_address + ':' + gw_port + '/wifidog/auth?token=' + token
            with closing(db.cursor()) as cr:
                wifidog_clients = db.get('wifidog.clients')
                wifidog_clients_ids = wifidog_clients.search(cr, SUPERUSER_ID, [('token', '=', token)])
                if not wifidog_clients_ids:
                    #继续查找是否有未认证的mac地址
                    wifidog_clients_ids = wifidog_clients.search(cr, SUPERUSER_ID, [('mac', '=', mac_address), ('token', '=', None)])
                    if wifidog_clients_ids:
                        wifidog_clients.write(cr, SUPERUSER_ID, wifidog_clients_ids, {'token': str(token),
                                                                                      'user_id': uid, 'ip': ip})
                    else:
                        wifidog_clients.create(cr, SUPERUSER_ID, {'token': str(token), 'user_id': uid, 'mac': mac_address, 'ip': ip})
                else:
                    wifidog_clients.write(cr, SUPERUSER_ID, wifidog_clients_ids, {'token': str(token),
                                                                                  'user_id': uid, 'mac': mac_address, 'ip': ip})
                cr.commit()
            return werkzeug.utils.redirect(url)
        else:
            template = env.get_template('wifidog/wifidog_code_login.html')
            wifidog_obj = db.get('wifidog.clients')
            with closing(db.cursor()) as cr:
                wifidog_obj_ids = wifidog_obj.search(cr, SUPERUSER_ID, [('mac', '=', mac_address)])
                if not wifidog_obj_ids and mac_address:
                    print '-------no mac_address exists, create it:', mac_address
                    wifidog_obj.create(cr, SUPERUSER_ID, {'mac': mac_address, 'ip': ip})
                    cr.commit()
            return template.render({'mac': mac_address, 'gw_address': gw_address, 'gw_port': gw_port, 'url': kw.get('url')})

    # wifidog认证
    @http.route('/weixin/wifidog_auth', auth='public')
    def weixin_wifidog_auth(self, **kw):
        db_name = request.session.db
        stage = kw.get('stage')  # counters计时、login登录、logout登出
        res = 'Auth: 0'
        if stage:
            # 需要检查mac、token、uid是否存在于wifidog_clients表
            # 如果存在返回Auth: 1
            if stage == 'login' or stage == 'counters':
                db = RegistryManager.get(db_name)
                wifidog_clients = db.get('wifidog.clients')
                with closing(db.cursor()) as cr:
                    wifidog_client_id = wifidog_clients.search(cr, SUPERUSER_ID, [('token', '=', kw.get('token'))])
                    if wifidog_client_id:
                        res = 'Auth: 1'
                    else:
                        res = 'Auth: 0'
        return res

    # weixin 认证 跳转
    @http.route('/weixin/wifidog_redirect', auth='weixin')
    def weixin_wifidog_redirect(self, **kw):
        uid = request.session.uid
        if uid:
            # partner_obj = openerp.registry(db_name)['res.partner']
            return werkzeug.utils.redirect(openerp.tools.config.get('wifidog_url'))
        else:
            # 微信认证失败
            return "微信认证失败"

    @http.route('/weixin/wifidog_message', auth='public')
    def wifidog_message(self, **kw):
        return kw.get('message')

    # wifidog portal

    @http.route('/weixin/wifidog_portal', auth='public')
    def weixin_wifidog_portal(self, **kw):
        # db_name = request.session.db
        template = env.get_template('wifidog/wifidog_login_state.html')
        return template.render({
            'state': 'success',
            'title': '认证结果',
            'body': '认证结果'
        })

    @http.route('/test/view/customer-list', auth='public')
    def customerList(self, **kw):
        # partner_obj = openerp.registry(db_name)['res.partner']
        # partner_obj.search()
        template = env.get_template("customer-list.html")
        return template.render({
            'options': {},
        })

    @http.route('/test/view/<page>', auth='public')
    def index(self, page, **kw):
        template = env.get_template(page + ".html")
        return template.render({
            'options': {},
        })

    @http.route(['/weixin/wifidog_mac_auth', '/weixin/wifidog_mac_auth/<string:mac>'], auth='weixin')
    def wifidog_mac_auth(self, **kw):
        db_name = request.session.db
        uid = request.session.uid
        mac_address = kw.get('mac')
        if uid and mac_address:
            token_md5 = hashlib.md5()
            token_md5.update('%s%s' % (mac_address, uid))
            token = token_md5.hexdigest()
            # print token, mac_address, uid, '-----', kw
            # url = 'http://' + gw_address + ':' + gw_port + '/wifidog/auth?token=' + token
            db = RegistryManager.get(db_name)
            with closing(db.cursor()) as cr:
                wifidog_clients = db.get('wifidog.clients')
                wifidog_clients_ids = wifidog_clients.search(cr, SUPERUSER_ID, [('token', '=', token)])
                if not wifidog_clients_ids:
                    wifidog_clients.create(cr, SUPERUSER_ID, {'token': str(token), 'user_id': uid, 'mac': mac_address})
                else:
                    wifidog_clients.write(cr, SUPERUSER_ID, wifidog_clients_ids, {'token': str(token), 'user_id': uid})
                cr.commit()
                db.get('bus.bus').sendone(cr, SUPERUSER_ID, 'wifidog_auth', {'mac': mac_address, 'token': token})
            template = env.get_template('wifidog/wifidog_login_state.html')
            return template.render({
                'state': 'success',
                'title': '认证结果',
                'body': '认证结果'
            })
        else:
            template = env.get_template('wifidog/wifidog_login_state.html')
            return template.render({
                'state': 'fail',
                'title': '认证结果',
                'body': '认证结果'
            })
    #####################################################################
    #
    # 生成session md5 二维码
    #
    #####################################################################

    @http.route('/weixin/wifidog_login_qrcode', auth='public')
    def wifidog_login_qrcode(self, type, mac, width=600, height=100):
        """Contoller able to render barcode images thanks to reportlab.
        Samples:
            <img t-att-src="'/report/barcode/QR/%s' % o.name"/>
            <img t-att-src="'/report/barcode/?type=%s&amp;value=%s&amp;width=%s&amp;height=%s' %
                ('QR', o.name, 200, 200)"/>

        :param type: Accepted types: 'Codabar', 'Code11', 'Code128', 'EAN13', 'EAN8', 'Extended39',
        'Extended93', 'FIM', 'I2of5', 'MSI', 'POSTNET', 'QR', 'Standard39', 'Standard93',
        'UPCA', 'USPS_4State'
        """
        # db = openerp.registry(db_name)
        # 商城用户检查
        try:
            width, height = int(width), int(height)
            url = "http://" + request.httprequest.host + "/weixin/wifidog_mac_auth/%s" % (mac,)
            barcode = createBarcodeDrawing(
                type, value=url, format='png', width=width, height=height
            )
            barcode = barcode.asString('png')
        except (ValueError, AttributeError):
            raise openerp.exceptions.HTTPException(description='Cannot convert into barcode.')
        return request.make_response(barcode, headers=[('Content-Type', 'image/png')])
